package lab03.test06;

import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 星月 on 2017/12/05.
 */
public class Test06 {
    public static void main(String[] args) {
        String path = "F:\\java实验三\\hello.txt";
        RandomAccessFile file = null;

        Map<String, Integer> map = new HashMap<String,Integer>();
        List<Map.Entry<String, Integer>> list = null;

        try {
            file = new RandomAccessFile(path, "r");
            String line = null;
            int count = 0;

            try {
                while ((line = file.readLine()) != null) {
                    count = count + 1;
                    //先要判断map中有没有这个key，没有直接讲value赋值为1
                    if (map.get(line) == null) {
                        map.put(line, 1);
                    } else {
                        map.put(line, map.get(line) + 1);
                    }
                    list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()) {
                        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                            int t = -o1.getValue().compareTo(o2.getValue());
                            if (t == 0)
                                return o1.getKey().compareTo(o2.getKey());
                            return t;
                        }
                    };
                }
                System.out.println("总共出现了：" + count + "个单词");
                System.out.println("总共有：" + map.size() + "个不同的单词。");
                for (Map.Entry<String, Integer> entry : list) {
                    System.out.println(entry.getKey() + "\t\t" + entry.getValue());
                }
                } catch (FileNotFoundException e) {
                e.printStackTrace();
                 }
            } catch (IOException e) {
            e.printStackTrace();
            }
    }
}
